package leetcode.sword;

import java.util.ArrayList;

public class Solution57_2 {

    public static void main(String[] args) {
        int[][] res = new Solution57_2().findContinuousSequence(15);
        System.out.println(res);
    }

    public int[][] findContinuousSequence1(int target) {
        ArrayList<int[]> total = new ArrayList<>();
        for (int i = 1; i <= target/2; i++) {
            int curSum = 0;
            for (int j = i; j <=target/2+1; j++) {
                curSum += j;
                if(curSum>target) break;
                if(curSum==target) total.add(new int[]{i, j});
            }
        }
        int[][] res = new int[total.size()][];
        for (int i = 0; i < total.size(); i++) {
            int[] tmp = new int[total.get(i)[1]-total.get(i)[0]+1];
            for (int j = total.get(i)[0],k=0; j < total.get(i)[1]+1; j++,k++) tmp[k] = j;
            res[i] = tmp;
        }
        return res;
    }

    public int[][] findContinuousSequence(int target) {
        ArrayList<int[]> total = new ArrayList<>();
        int i = 1, j = 2, sum = 0;
        while (i<j){
            sum = (i+j)*(j-i+1)/2;
            if(sum>target){
                i++;
            }else if(sum<target){
                j++;
            }else {
                int[] tmp = new int[j-i+1];
                for (int k = i; k <= j; k++) {
                    tmp[k-i] = k;
                }
                total.add(tmp);
                i++;
            }
        }
        return total.toArray(new int[total.size()][]);
    }
}
